package com.th.basemodel.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Context.ACTIVITY_SERVICE
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.hardware.SensorManager
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Proxy
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.os.SystemClock
import android.provider.Settings
import android.provider.Settings.SettingNotFoundException
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.DisplayMetrics
import java.io.File
import java.net.NetworkInterface
import java.net.SocketException
import java.time.Instant
import java.util.Locale
import java.util.TimeZone
import kotlin.math.pow
import kotlin.math.sqrt


object DeviceInfoUtil {

    fun upload(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("each", deviceBase(context))
            put("journeys", screen(context))
            put("relocated", fileInfo())
            put("opening", storage(context))
            put("downtown", locale(context))
            put("exhibition", battery(context))
            put("review", dbm())
            put("commented", someInfo(context))
            put("concept", general(context))
            put("exploring", mutableListOf<Any>())
            put("meets",networkInfo(context))
            put("fantasy",sensorList(context))
            put("colors",imeiAndLineNumber(context))
        }
    }

    private fun imeiAndLineNumber(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("paintings", imei(context)) //imei
            put("ink", simSerialNumber(context)) //sim卡序列号
            put("integrating", line1Number(context)) //sms卡1的手机号
        }
    }

    private fun line1Number(context: Context): String {
        try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return telephonyManager.line1Number
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun simSerialNumber(context: Context): String {
        try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            return telephonyManager.simSerialNumber
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imei(context: Context): String {
        return try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            telephonyManager!!.imei
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun sensorList(context: Context): MutableList<MutableMap<String,Any>> {
        val list = mutableListOf<MutableMap<String, Any>>()

        val sensorManager =
            context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val sensorList = sensorManager.getSensorList(android.hardware.Sensor.TYPE_ALL)

        for (sensor in sensorList) {
            var bean = mutableMapOf<String,Any>().apply {
                put("enters", sensor.minDelay.toString()) //minDelay
                put("drowns", sensor.vendor) //vendor
                put("providing", sensor.name) //名称
                put("accidentally", sensor.maximumRange.toString()) //maxRange
                put("girl", sensor.power.toString()) //power
                put("linkage", sensor.type.toString()) //类型
                put("little", sensor.type.toString()) //版本
                put("interpretation", sensor.resolution.toString()) //resolution
            }
            list.add(bean)
        }
        return list
    }

    private fun networkInfo(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("where", network_type(context)) //网络类型
            put("advocating", getMacAddress(context)) //mac 地址
//            put("ip", ip()) //局域网ip
//            put("configured_wifi", ip()) //局域网ip
//            put("current_wifi", current_wifi()) //局域网ip
//            put("wifi_count", wifi_count(context)) //局域网ip
        }
    }


    private fun ip(): String {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    if (!address.isLoopbackAddress && address.hostAddress.indexOf(':') == -1) {
                        return address.hostAddress
                    }
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        return ""
    }

    fun getMacAddress(context: Context): String {
       try {
           val wifiManager =
               context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
           if (wifiManager != null) {
               val wifiInfo = wifiManager.connectionInfo
               if (wifiInfo != null) {
                   return wifiInfo.macAddress
               }
           }
           return ""
       } catch (e: Exception) {
           e.printStackTrace()
       }
        return ""
    }

    fun network_type(context: Context): String {
        try {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (connectivityManager != null) {
                val activeNetwork = connectivityManager.activeNetworkInfo
                if (activeNetwork != null && activeNetwork.isConnected) {
                    return if (activeNetwork.type == ConnectivityManager.TYPE_WIFI) {
                        "Wi-Fi"
                    } else if (activeNetwork.type == ConnectivityManager.TYPE_MOBILE) {
                        val networkType = activeNetwork.subtype
                        when (networkType) {
                            TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> "2G"
                            TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> "3G"
                            TelephonyManager.NETWORK_TYPE_LTE -> "4G"
                            TelephonyManager.NETWORK_TYPE_NR -> "5G"
                            else -> "Unknown"
                        }
                    } else {
                        "Other"
                    }
                }
            }
            return ""
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun general(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put(
                "frame",
                (System.currentTimeMillis() - SystemClock.elapsedRealtime()).toString()
            )//System.currentTimeMillis() - SystemClock.elapsedRealtime()
            put("every", SystemClock.elapsedRealtime())//SystemClock.elapsedRealtime()
            put("art", SystemClock.uptimeMillis())//SystemClock.uptimeMillis()
            put("vitality", is_usb_debug(context))//是否打开USB调试
            put("injecting", can_call_phone(context))//是否可以打电话(1,yes)0,no)
            put("dimensional", is_using_vpn(context))//是否使用vpn
            put("presents", "1")// 连接到设备的键盘种类
            put(
                "particle", if (is_root_jailbreak(context)) {
                    "1"
                } else {
                    "0"
                }
            )//是否root(1,yes)0,no)
            put("call", is_using_proxy_port(context))//是否使用端口代理
            put("technique", is_mock_location(context))//是否模拟位置(1,yes)0,no)
        }
    }

    private fun is_mock_location(context: Context): String {
        return try {
            val isMockLocationEnabled =
                Settings.Secure.getString(
                    context.contentResolver,
                    Settings.Secure.ALLOW_MOCK_LOCATION
                ) != "0"
            if (isMockLocationEnabled) {
                "1"
            } else {
                "0"
            }
        } catch (e: Exception) {
            e.printStackTrace()
            "0"
        }
    }

    fun is_using_proxy_port(context: Context?): Boolean {
       try {
           val proxyHost: String = Proxy.getHost(context)
           val proxyPort: Int = Proxy.getPort(context)
           return !TextUtils.isEmpty(proxyHost) && proxyPort != -1
       } catch (e: Exception) {
           e.printStackTrace()
       }
        return false
    }

    fun is_root_jailbreak(context: Context): Boolean {
        val knownRootAppsPackages = arrayOf(
            "com.noshufou.android.su", "com.thirdparty.superuser",
            "eu.chainfire.supersu", "com.koushikdutta.superuser",
            "com.zachspong.temprootremovejb", "com.ramdroid.appquarantine"
        )
        val paths = arrayOf(
            "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su",
            "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su",
            "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su"
        )
        for (packageName in knownRootAppsPackages) {
            try {
                if (context.packageManager.getPackageInfo(packageName, 0) != null) {
                    return true
                }
            } catch (e: PackageManager.NameNotFoundException) {
                // Package not found, continue checking
            }
        }
        for (path in paths) {
            if (File(path).exists()) {
                return true
            }
        }
        return false
    }

    private fun is_using_vpn(context: Context): Boolean {
        try {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                    ?: return false

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val activeNetwork = connectivityManager.activeNetwork
                if (activeNetwork != null) {
                    val networkCapabilities =
                        connectivityManager.getNetworkCapabilities(activeNetwork)
                    return networkCapabilities != null && networkCapabilities.hasTransport(
                        NetworkCapabilities.TRANSPORT_VPN
                    )
                }
            } else {
                val networks = connectivityManager.allNetworks
                for (network in networks) {
                    val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
                    if (networkCapabilities != null && networkCapabilities.hasTransport(
                            NetworkCapabilities.TRANSPORT_VPN
                        )
                    ) {
                        return true
                    }
                }
            }

            return false
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun can_call_phone(context: Context): Int {
        try {
            val packageManager = context.packageManager
            return if (packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
                1
            } else {
                0
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun is_usb_debug(context: Context): Int {
        try {
            val is_usb_debug = try {
                Settings.Global.getInt(context.contentResolver, Settings.Global.ADB_ENABLED, 0) > 0
            } catch (e: SettingNotFoundException) {
                e.printStackTrace()
                false
            }
            return if (is_usb_debug) {
                1
            } else {
                0
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun someInfo(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("ending", appTotalMemory(context))//app整个内存
            put("good", appFreeMemory(context))//app空闲内存
            put("very", Runtime.getRuntime().maxMemory().toString())//app最大内存
        }
    }

    private fun appFreeMemory(context: Context): String {
        return try {
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager!!.getMemoryInfo(memoryInfo)
            memoryInfo.availMem.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun appTotalMemory(context: Context): String {
        return try {
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager!!.getMemoryInfo(memoryInfo)
            memoryInfo.totalMem.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun dbm(): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("fan", "0")//手机信号级别
            put("linkage", "0")//手机信号类型
            put("review", "0")//手机信号强度
        }
    }

    private fun battery(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("survivors", battery_pct(context))//电池百分比
            put("holocaust", battery_level(context))//当前电量
            put(
                "commemorate", if (is_usb_charge(context)) {
                    1
                } else {
                    0
                }
            )//是否USB充电(1,yes)0,no)
            put("recommending", battery_max(context))//最大电量
            put(
                "worth", if (is_ac_charge(context)) {
                    1
                } else {
                    0
                }
            )//是否交流充电(1,yes)0,no)
            put(
                "douban", if (is_charging(context)) {
                    1
                } else {
                    0
                }
            )   //是否正在充电(1,yes)0,no)
        }
    }

    private fun is_charging(context: Context): Boolean {
        try {
            // 创建一个 IntentFilter 来获取 ACTION_BATTERY_CHANGED 广播
            val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            // 注册一个接收器来获取电池状态的 Intent
            val batteryStatus: Intent = context.registerReceiver(null, ifilter)!!

            // 从 Intent 中提取充电状态信息
            val status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
            // 检查充电状态是否为充电中或充满电
            return status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun is_ac_charge(context: Context): Boolean {
        try {
            // 创建一个 IntentFilter 来获取 ACTION_BATTERY_CHANGED 广播
            val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            // 注册一个接收器来获取电池状态的 Intent
            val batteryStatus: Intent = context.registerReceiver(null, ifilter)!!
            // 从 Intent 中提取充电状态信息
            val chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
            // 检查充电状态是否为通过 AC 充电
            return chargePlug == BatteryManager.BATTERY_PLUGGED_AC
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    private fun battery_max(context: Context?): Int {
        val mPowerProfile: Any
        var batteryCapacity = 0.0
        val POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile"
        try {
            mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
                .getConstructor(Context::class.java)
                .newInstance(context)
            batteryCapacity = Class
                .forName(POWER_PROFILE_CLASS)
                .getMethod("getBatteryCapacity")
                .invoke(mPowerProfile) as Double
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return batteryCapacity.toInt()
    }

    private fun is_usb_charge(context: Context): Boolean {
        val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        val batteryStatus: Intent = context.registerReceiver(null, ifilter)!!

        val chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)

        return chargePlug == BatteryManager.BATTERY_PLUGGED_USB
    }

    private fun battery_level(context: Context): Int {
        try {
            val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            val batteryStatus: Intent = context.registerReceiver(null, ifilter)!!

            return batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun battery_pct(context: Context): Int {
        try {
            val ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            val batteryStatus: Intent = context.registerReceiver(null, ifilter)!!

            val level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
            val scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1)

            val batteryPct = level / scale.toFloat()
            return (batteryPct * 100).toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun locale(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("museum", Locale.getDefault().isO3Language)//语言环境的三字母缩写
            put("refugees", sim_country_iso(context))//sim卡的国家iso
            put("jewish", Locale.getDefault().displayLanguage)//此用户显示的语言环境语⾔的名称)
            put("shanghai", Locale.getDefault().language)//语言
            put("camps", network_operator_name(context))//网络运营商名称
            put("persons", TimeZone.getDefault().id)//时区的 ID
            put("displaced", Locale.getDefault().isO3Country)//此地区的国家/地区的缩写
        }
    }

    private fun network_operator_name(context: Context): String {
        try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            return telephonyManager!!.networkOperatorName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun sim_country_iso(context: Context): String {
        try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            return telephonyManager!!.simCountryIso.uppercase(Locale.getDefault())
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun storage(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("persecution", ram_total_size(context))//RAM内存大小
            put("nazi", ram_usable_size(context))//RAM内存可用大小
            put("thousands", memory_card_size())//内存卡大小
            put("sheltered", memory_card_size_use())//内存卡使用大小
            put("district", internal_storage_usable())//内存卡未使用大小
            put("hongkou", internal_storage_total()) //总存储大小
        }
    }

    private fun internal_storage_total(): Long {
        try {
            // 获取内部存储路径
            val path = Environment.getDataDirectory().path
            val statFs = StatFs(path)

            // 获取每个存储块的大小（字节）
            val blockSize = statFs.blockSizeLong

            // 获取存储块的总数
            val totalBlocks = statFs.blockCountLong


            // 计算总容量,
            return totalBlocks * blockSize
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun internal_storage_usable(): Long {
        try {
            // 获取内部存储路径
            val path = Environment.getDataDirectory().path
            val statFs = StatFs(path)

            // 获取每个存储块的大小（字节）
            val blockSize = statFs.blockSizeLong

            // 获取可用存储块的数量
            val availableBlocks = statFs.availableBlocksLong

            // 计算可用容量,
            return availableBlocks * blockSize
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun memory_card_size_use(): Long {
        return try {
            val externalStorage = Environment.getExternalStorageDirectory()
            externalStorage.usableSpace
        } catch (e: Exception) {
            e.printStackTrace()
            0
        }
    }

    private fun memory_card_size(): Long {
        return try {
            val externalStorage = Environment.getExternalStorageDirectory()
            externalStorage.totalSpace
        } catch (e: Exception) {
            e.printStackTrace()
            0
        }
    }

    private fun ram_usable_size(context: Context): String {
        try {
            val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager?
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager!!.getMemoryInfo(memoryInfo)
            return memoryInfo.availMem.toString() // 将字节转换为MB
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun ram_total_size(context: Context): String {
        try {
            val activityManager = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager?
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager!!.getMemoryInfo(memoryInfo)
            return memoryInfo.totalMem.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun fileInfo(): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("visitors", "0")
            put("nations", "0")
            put("hosted", "0")
            put("co", "0")
            put("march", "0")
            put("until", "0")
            put("run", "0")
        }
    }

    private fun screen(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("taking", context.resources.displayMetrics.densityDpi.toString())
            put("wwii", physicalSize(context))
            put("worldwide", context.resources.displayMetrics.scaledDensity)
            put("administration", context.resources.displayMetrics.density)
            put("rehabilitation", context.resources.displayMetrics.heightPixels)
            put("relief", context.resources.displayMetrics.ydpi)
            put("help", context.resources.displayMetrics.xdpi)
            put("rebuilt", context.resources.displayMetrics.widthPixels)
        }
    }

    private fun physicalSize(context: Context): String {
        try {
            // 获取屏幕尺寸
            val displayMetrics: DisplayMetrics = context.resources.displayMetrics
            val widthPixels = displayMetrics.widthPixels.toFloat()
            val heightPixels = displayMetrics.heightPixels.toFloat()
            val densityDpi = displayMetrics.densityDpi.toFloat()

            // 计算宽高的物理尺寸（英寸）
            val widthInches = widthPixels / densityDpi
            val heightInches = heightPixels / densityDpi

            // 计算对角线尺寸（英寸）
            val diagonalInches = sqrt(
                widthInches.toDouble().pow(2.0) + heightInches.toDouble().pow(2.0)
            )

            return diagonalInches.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return ""
    }

    private fun deviceBase(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().apply {
            put("supported", phone_type(context))
            put("together", isEmulator())
            put("miracle", AppUtil.adid)
            put("kranzler", Build.VERSION.RELEASE)
            put("david", Build.TIME.toString())
            put("historian", Build.TIME.toString())
            put("described", serial_number(context))
            put("feat", System.currentTimeMillis())
            put("remarkable", Build.MANUFACTURER)
            put("assistance", Build.BRAND)
            put("saving", Runtime.getRuntime().availableProcessors())
            put("thanks", Build.FINGERPRINT)
            put("themselves", createTime())
            put("survive", Build.VERSION.SDK_INT.toString())
            put("able", Build.MODEL)
            put(
                "hard", try {
                    Settings.Secure.getString(
                        context.getContentResolver(),
                        Settings.Secure.ANDROID_ID
                    )
                } catch (e: Exception) {
                    e.printStackTrace()
                    ""
                }
            )
            put("supporting", Build.BRAND)
            put("while", Build.BOARD)
            put("reach", "")
        }
    }

    private fun createTime(): Long {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Instant.now().epochSecond
            } else {
                0
            }
        } catch (e: Exception) {
            0
        }
    }


    private fun serial_number(context: Context): String {
        var serialNumber = ""
        try {
            serialNumber = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Build.getSerial()
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                Build.SERIAL
            } else {
                Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID)
            }
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
        return serialNumber
    }

    private fun isEmulator(): String {
        try {
            val is_simulator = (Build.FINGERPRINT.startsWith("generic")
                    || Build.FINGERPRINT.startsWith("unknown")
                    || Build.MODEL.contains("google_sdk")
                    || Build.MODEL.contains("Emulator")
                    || Build.MODEL.contains("Android SDK built for x86")
                    || Build.MANUFACTURER.contains("Genymotion")
                    || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                    || "google_sdk".equals(Build.PRODUCT))

            return if (is_simulator) {
                "1"
            } else {
                "0"
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return "0"
    }

    private fun phone_type(context: Context): String {
        return try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            telephonyManager!!.phoneType.toString()
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

}